package com.mall.common;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

public class TokenCache {
	
	private static Logger logger = LoggerFactory.getLogger(TokenCache.class);
	
	//LRU算法
	private static LoadingCache<String, String> cache = CacheBuilder.newBuilder()
			.initialCapacity(1000)		//设置cache的初始大小为10
			.maximumSize(1000) 			//设置缓存个数
			.expireAfterAccess(1, TimeUnit.HOURS)  //设置过期时间 :1个小时
 			.build(new CacheLoader<String,String>(){
				//默认的数据加载实现,当调用get取值的时候,如果key没有对应的值,就调用这个方法进行加载.
				@Override
				public String load(String s) throws Exception {
					return "null";
				}
				
			});
	
	public static void setKey(String key,String value){
		cache.put(key, value);
	}
	 
	public static String getKey(String key){
		String value = null;
		try{
			value = cache.get(key); 
			if("null".equals(value)){
				return null;
			} 
			return value;
			
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	
}
